package com.zl.learning.object.event;

import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import java.util.function.Function;

public class EventBus {

    public enum EventName {
        /**
         * 事件名称
         */
        WRITE_ZIP_SUCCESS,
        FTP_UPLOAD_SUCCESS
    }

    private static final ConcurrentHashMap<EventName, CopyOnWriteArrayList<Consumer<Object>>> SUBSCRIBERS = new ConcurrentHashMap<>();

    public static void on(EventName eventName, Consumer<Object> consumer) {
        SUBSCRIBERS.compute(eventName, (s, consumers) -> {
            if (consumers == null) {
                consumers = new CopyOnWriteArrayList<>();
            }
            consumers.add(consumer);
            return consumers;
        });
    }

    public static void publish(EventName event, Object content) {
        Optional.ofNullable(SUBSCRIBERS.get(event)).ifPresent(r -> r.forEach(c -> c.accept(content)));
    }


    private static final ConcurrentHashMap<EventName, Function<Object, Object>> eventMap = new ConcurrentHashMap<>();

    public static Object execute(EventName eventName, Object content) {
        return eventMap.get(eventName).apply(content);
    }

}
